<template>
    <div class="manage-basic-component">
        <el-row :gutter="20" class="container-fr">
            <el-col :span="12" class="container-fr">
                <div class="scroll-full">
                    <div class="component-info">
                        <el-button class="btn-fr edit-btn" type="danger" plain size="small" @click="editComponent">{{componentStatus === 'edit' ? '取消编辑' : '编辑'}} </el-button>
                        <el-button class="btn-fr edit-btn" type="danger" plain size="small" @click="importAttrJson">导入 </el-button>
                        <el-button class="btn-fr save-btn" type="danger" plain size="small" @click="saveComponent">保存 </el-button>
                        <h3 class="container-title">组件信息</h3>
                        <el-form ref="componentForm" :model="componentInfo" label-width="120px" :rules="componentRules" :hide-required-asterisk="true" size="mini">
                            <el-form-item label="组件所属: " prop="name">
                                <el-select v-model="componentInfo.componentType" placeholder="请选择类别">
                                    <el-option
                                        v-for="item in componentType"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="组件名称: " prop="name" >
                                <el-input v-if="componentStatus !== 'edit'" v-model="componentInfo.name" placeholder="请输入组件名称"></el-input>
                                <el-select v-else v-model="componentInfo.id" placeholder="请选择组件" @change="nameChange">
                                    <el-option
                                        v-for="item in componentList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="组件类型: " prop="type">
                                <el-input v-model="componentInfo.type" placeholder="请输入组件类型"></el-input>
                            </el-form-item>
                            <el-form-item label="组件路径: " prop="type">
                                <el-input v-model="componentInfo.path" placeholder="请上传组件"></el-input>
                            </el-form-item>
                        </el-form>
                        <!-- 配置属性 -->
                        <div class="attribute-container">
                            <el-button type="danger" plain size="small" @click="dialogFormVisible = true">选择属性 </el-button>
                            添加必须属性<el-switch v-model="newAttr.requiredAttr"></el-switch>
                            <div class="attr-fr attr-basic" v-if="componentInfo.attribute.basicAttr">
                                <h3 class="box-title">基础属性</h3>
                                <ul class="attribute-list">
                                    <li class="item" v-for="(item, index) in componentInfo.attribute.basicAttr" :key="index">
                                        <span class="label">{{ item.label }}: </span>
                                        <el-input class="change-default" v-model="item.value" :placeholder="'请输入' + item.label" />
                                    </li>
                                </ul>
                            </div>
                            <div class="attr-fr attr-bool" v-if="componentInfo.attribute.booleanAttr">
                                <h3 class="box-title">布尔属性</h3>
                                <ul class="attribute-list">
                                    <li class="item" v-for="(item, index) in componentInfo.attribute.booleanAttr" :key="index + 100">
                                        <span class="label">{{ item.label }}: </span>
                                        <el-switch v-model="item.value" />
                                    </li>
                                </ul>
                            </div>
                            <div class="attr-fr attr-select" v-if="componentInfo.attribute.selectAttr">
                                <h3 class="box-title">选择属性</h3>
                                <ul class="attribute-list">
                                    <li class="item" v-for="(item, index) in componentInfo.attribute.selectAttr" :key="index + 100">
                                        <span class="label">{{ item.label }}: </span>
                                        <el-select v-model="item.value" placeholder="请选择默认属性">
                                            <el-option v-for="child in JSON.parse(item.extendData)" :key="child['value'] ? child['value'] : child['key']" :label="child['label'] ? child['label'] : child['name']" :value="child['value'] ? child['value'] : child['key']"></el-option>
                                        </el-select>
                                    </li>
                                </ul>
                            </div>
                            <div class="attr-fr attr-expand" v-if="componentInfo.attribute.ruleAttr">
                                <h3 class="box-title">额外属性</h3>
                                <ul class="attribute-list">
                                    <li class="item" v-for="(item, index) in componentInfo.attribute.ruleAttr" :key="index + 10000">
                                        <span class="label">{{ item.label }}: </span>
                                        <el-input class="change-default" v-model="item.value" :placeholder="'请输入' + item.label" />
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </el-col>
            <!-- 右侧属添加属性 -->
            <el-col :span="12" class="container-fr">
                <div class="scroll-full">
                    <div class="component-attribute">
                        <h3 class="container-title">添加属性</h3>
                        <el-form :model="newAttr" label-width="120px" size="mini" ref="ruleForm">
                            <el-form-item label="属性名称: ">
                                <el-input v-if="!attrStatus" v-model="newAttr.label"></el-input>
                                <el-select v-else v-model="newAttr.id" placeholder="请选择属性" @change="attrChange">
                                    <el-option
                                        v-for="item in attributeList"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="属性所属: ">
                                <el-select v-model="newAttr.attrType" placeholder="Select">
                                    <el-option v-for="item in attrType" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="属性键名: ">
                                <el-input v-model="newAttr.key"></el-input>
                            </el-form-item>
                            <el-form-item label="属性类型: ">
                                <el-input v-model="newAttr.type"></el-input>
                            </el-form-item>
                            <el-form-item label="属性默认值: ">
                                <el-input v-model="newAttr.value"></el-input>
                            </el-form-item>
                            <el-form-item label="默认值类型: ">
                                <el-select v-model="newAttr.valueType" placeholder="Select">
                                    <el-option v-for="item in defaultValType" :key="item.key" :label="item.name" :value="item.key"> </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="属性静态额外值: ">
                                <el-input type="textarea" v-model="newAttr.extendData"></el-input>
                            </el-form-item>
                        </el-form>
                        <div class="btn-ctrl">
                            <el-button class="btn-fr" type="primary" size="small" @click="addAttribute">{{attrStatus ? '保存' : '添加'}}</el-button>
                            <el-button class="btn-fr" type="info" plain size="small" @click="resetForm('ruleForm')">重置 </el-button>
                            <el-button class="btn-fr edit-btn" type="danger" plain size="small" @click="editAttribut">{{attrStatus ? '取消编辑' : '编辑'}} </el-button>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <AttrDialog v-model:dialogFormVisible="dialogFormVisible" :defaultVal="selectAttribute" :componentAttr="componentAttr" @change="selectFormAttr" @edit="editAttr"></AttrDialog>
        <EditAttrDialog v-model:dialogFormVisible="editAttrDialogStatus" :data="editAttrDialogData" @save="saveEditAttr"></EditAttrDialog>
        <ImportAttrDialog v-model:dialogStatus="importAttrDialog"></ImportAttrDialog>
    </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useStore } from 'vuex'
// import {
//     FormAttr as attributeArr
// } from 'static/js/form.js';
import { basicComponent } from '@/api/index.js'
import { nameIsNoEmpty, typeIsNoEmpty } from '@/utils/common/rules.js'
import EditAttrDialog from './components/EditAttrDialog.vue'
import AttrDialog from './components/AttrDialog.vue'
import ImportAttrDialog from './components/ImportAttrDialog.vue'
// import attrjson from './u.json'
export default {
    components: {
        EditAttrDialog,
        AttrDialog,
        ImportAttrDialog
    },
    setup() {
        const store = useStore(); // 使用useStore方法
        const userInfo = computed(() => store.state.userInfo);
        const loginStatus = computed(() => store.state.loginStatus);
		let editType = ref('') // 正在编辑的属性类型
        // 组件表单规则
        let componentRules = reactive({
            name: [
                {
                    required: true,
                    validator: nameIsNoEmpty,
                    trigger: ['blur']
                }
            ],
            type: [
                {
                    required: true,
                    validator: typeIsNoEmpty,
                    trigger: ['blur']
                }
            ]
        })
        // 组件状态,edit or add 默认：add
         let componentStatus = ref('add');
        // 组件所属类别
        let componentType = ref([])
        // 已保存的组件列表
        let componentList = ref([])
        // 新增组件信息
        let componentInfo = ref({
            id: '',
            componentType: '', // 组件类别
            name: '',
            type: '',
            path: '',
            attribute: {
                basicAttr: {},
                booleanAttr: {},
                ruleAttr: {},
                selectAttr: {},
                requiredAttr: {}
            }
        })
        // 添加新属性
        // 属性类型
        let attrType = ref([])
        let attrStatus = ref(false) // 属性状态
        const defaultValType = ref([
            {
                name: '字符串',
                key: 'string'
            },
            {
                name: '数值型',
                key: 'number'
            },
            {
                name: '布尔型',
                key: 'boolean'
            },
            {
                name: '对象类型',
                key: 'object'
            }
        ])
        let selectAttribute = ref([]) // 选中的属性
        let dialogFormVisible = ref(false) // 表单属性选择弹窗状态
        let editAttrDialogStatus = ref(false) // 编辑表单属性弹窗状态
        let importAttrDialog = ref(false); // 导入弹窗状态
        let editAttrDialogData = ref({}) // 编辑属性数据
        let localAttr = JSON.parse(localStorage.getItem('formAttribute'))
        // 表单属性
        let componentAttr = ref([])
        // 属性列表
        let attributeList = ref([])
        // 定义方法
        // 获取组件类别列表
        function getComponentTypeList() {
            let param = {
                pageNum: 1,
                pageSize: 10000
            }
            basicComponent.getBasicComponentTypeList(param).then((res) => {
                if (res.status === 1) {
                    console.log(res.data.list)
                    componentType.value = res.data.list
                }
            })
        }
        // 获取组件列表
        function getComponentList() {
            let param = {
                pageNum: 1,
                pageSize: 10000
            }
            basicComponent.getComponentList(param).then((res) => {
                if (res.status === 1) {
                    componentList.value = res.data.list
                }
            })
        }
        // 获取属性类型
        function getAttrType() {
            let param = {
                pageNum: 1,
                pageSize: 10000
            }
            basicComponent.getBasicComponentAttrType(param).then((res) => {
                if (res.status === 1) {
                    let temp = []
                    res.data.list.map((item) => {
                        componentInfo.value.attribute[item.type] = {}
                        temp.push({
                            label: item.name,
                            value: item.id,
                            type: item.type
                        })
                    })
                    attrType.value = temp
                }
            })
        }
        // 编辑属性
        function editComponent() {
            componentStatus.value = componentStatus.value === 'edit' ? 'add' : 'edit'
        }
        // 获取表单属性列表
        function getAttributeList() {
            let param = {
                pageNum: 1,
                pageSize: 100
            }
            basicComponent.getBasicComponentAttr(param).then((res) => {
                console.log(res)
                if (res.status === 1) {
                    let temp = {}
                    res.data.list.map(item => {
                        switch (item.valueType) {
                            case 'string':
                                item.value = (typeof item.value !== 'string') ? '' + item.value : item.value
                                break
                            case 'number':
                                item.value = (typeof item.value !== 'number') ? parseFloat(item.value) : item.value
                                break
                            case 'boolean':
                                item.value = (typeof item.value !== 'boolean') ? item.value === 'true' : item.value
                                break
                            case 'object':
                                item.value = (typeof item.value !== 'object') ? JSON.parse(item.value) : item.value
                                break
                        }
                    })
                    attributeList.value = res.data.list
                    res.data.list.map((item) => {
                        if (!temp[item.attrTypeType]) {
                            temp[item.attrTypeType] = {}
                        }
                        temp[item.attrTypeType][item.keyId] = {
                            id: item.id,
                            key: item.keyId,
                            label: item.label,
                            value: item.value,
                            type: item.type,
                            attrType: item.attrTypeType,
                            extendData: item.extendData
                        }
                    })
                    // for (let key in attrjson.attribute) {
                    //     temp[attrjson.attribute[key].attributeType][attrjson.attribute[key].key] = {
                    //         id: attrjson.attribute[key].key,
                    //         key: attrjson.attribute[key].key,
                    //         label: attrjson.attribute[key].label,
                    //         value: attrjson.attribute[key].value,
                    //         type: attrjson.attribute[key].type,
                    //         attrType: attrjson.attribute[key].attributeType,
                    //         extendData: attrjson.attribute[key].extendData
                    //     }
                    //     selectAttribute.value.push(attrjson.attribute[key].key)
                    // }
                    componentAttr.value = temp
                    // console.log('shuxing', attrjson.attribute, componentAttr.value)
                }
            })
        }
        // 组件选择改变
        function nameChange(e) {
            const temp = componentList.value.find(item => {
                return item.id === e
            })
            if (temp) {
                componentInfo.value.id = temp.id
                componentInfo.value.name = temp.name
                componentInfo.value.type = temp.type
                componentInfo.value.path = temp.fileName
                componentInfo.value.componentType = temp.componentType
                let attrList = JSON.parse(temp.attribute)
                for (let key in attrList) {
                    if ((attrList[key]['attrType'] && attrList[key].attrType !== 'requiredAttr') || (attrList[key]['attributeType'] && attrList[key].attributeType !== 'requiredAttr')) {
                        if (attrList[key].attributeType && attrList[key].attributeType !== 'requiredAttr') {
                            componentInfo.value.attribute[attrList[key].attributeType][key] = attrList[key]
                            componentAttr.value[attrList[key].attributeType][key] = attrList[key]
                            selectAttribute.value.push(key)
                        } else {
                            componentInfo.value.attribute[attrList[key].attrType][key] = attrList[key]
                            componentAttr.value[attrList[key].attrType][key] = attrList[key]
                            selectAttribute.value.push(key)
                        }
                    }
                }
                
            }
        }
        // 添加属性到属性选择弹窗列表
        function addAttrToList(list) {
            console.log('添加的属性', list)
        }
        // 编辑属性
        function editAttribut() {
            attrStatus.value = !attrStatus.value
        }
        // 左侧编辑属性
        function editAttr(item) {
            for (let key in item) {
                editAttrDialogData.value[key] = item[key]
            }
            editAttrDialogData.value.attrType = item.attributeType
            editType.value = editAttrDialogData.value.attrType
            editAttrDialogStatus.value = true
        }
        // 左侧属性保存编辑
        function saveEditAttr(item) {
            console.log('--', item, componentAttr.value)
            componentAttr.value[item.attrType][item.key] = JSON.parse(JSON.stringify(item))
            console.log(editType.value, item.attrType)
			editType.value !== item.attrType && delete componentAttr.value[editType.value][item.key]
        }
        // 导入json
        function importAttrJson() {
            importAttrDialog.value = true
        }
        // 运行
        getAttrType()
        getAttributeList()
        getComponentTypeList()
        getComponentList()

        return {
            componentInfo,
            componentAttr,
            dialogFormVisible,
            selectAttribute,
            attrType,
            componentRules,
            componentType,
            editComponent,
            componentList,
            componentStatus,
            nameChange,
            editAttribut,
            attributeList,
            attrStatus,
            defaultValType,
            userInfo,
            getAttributeList,
            editAttrDialogStatus,
            editAttrDialogData,
            editAttr,
            saveEditAttr,
			getComponentList,
            importAttrJson,
            importAttrDialog
        }
    },
    data() {
        return {
            newAttr: {
                id: '',
                requiredAttr: false,
                attrType: '',
                attrTypeName: '',
                key: '',
                replaceKey: '',
                label: '',
                type: '',
                value: '',
                valueType: '',
                extendData: ''
            }
        }
    },
    methods: {
        // 确认选择的属性
        selectFormAttr(v) {
            this.selectAttribute = v;
            this.dialogFormVisible = false
            for (let key in this.componentInfo.attribute) {
                this.componentInfo.attribute[key] = {}
            }
            // 基础属性
            for (let type in this.componentAttr) {
                for (let key in this.componentAttr[type]) {
                    if (this.selectAttribute.indexOf(key) > -1) {
                        this.componentInfo.attribute[type][key] = JSON.parse(JSON.stringify(this.componentAttr[type][key]))
                    }
                }
            }
        },
        // 属性选择
        attrChange(e) {
            console.log(e)
            if (this.attrStatus) {
                let cur = this.attributeList.find(item => {
                    return item.id === e
                })
                if (cur) {
                    this.newAttr.id = cur.id
                    this.newAttr.attrType = cur.attributeType
                    this.newAttr.key = cur.keyId
                    this.newAttr.label = cur.label
                    this.newAttr.type = cur.type
                    this.newAttr.value = cur.value
                    this.newAttr.valueType = cur.valueType
                    this.newAttr.extendData = cur.extendData
                }
            }
        },
        // 添加属性
        addAttribute() {
            let exData = null
            try {
                exData = JSON.parse(this.newAttr.extendData)
            } catch (e) {
                exData = null
            }
            let param = {
                id: this.newAttr.id,
                keyId: this.newAttr.key,
                replaceKey: this.newAttr.replaceKey,
                label: this.newAttr.label,
                value: this.newAttr.value,
                valueType: this.newAttr.valueType,
                type: this.newAttr.type,
                extend: this.newAttr.extendData,
                attributeType: this.newAttr.attrType,
                phone: this.userInfo.userId
            }
            let func = param.id ? basicComponent.putBasicComponentAttr : basicComponent.addBasicComponentAttr
            func(param).then((res) => {
                if (res.status === 1) {
                    for (let i in this.attrType) {
                        if (this.attrType[i].value === this.newAttr.attrType) {
                            if (!this.componentAttr[this.attrType[i].type]) {
                                this.componentAttr[this.attrType[i].type] = {}
                            }
                            param.key = param.keyId
                            this.componentAttr[this.attrType[i].type][this.newAttr.key] = param
                        }
                    }
                    this.resetForm('ruleForm')
                    // localStorage.setItem('formAttribute', JSON.stringify(this.componentAttr))
                    this.$message({
                        message: '保存属性成功！',
                        type: 'success'
                    })
                    this.getAttributeList()
                } else {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })
        },
        resetForm(formName) {
            for (let key in this.$refs[formName].model) {
                this.$refs[formName].model[key] = ''
            }
        },
        // 保存组件
        saveComponent() {
            this.$refs['componentForm'].validate(async (valid) => {
                if (valid) {
                    let attrList = {
                        ...this.componentInfo.attribute.basicAttr,
                        ...this.componentInfo.attribute.booleanAttr,
                        ...this.componentInfo.attribute.ruleAttr,
                        ...this.componentInfo.selectAttr
                    }
                    if (this.newAttr.requiredAttr) {
                        attrList = {
                            ...attrList,
                            ...this.componentAttr.requiredAttr
                        }
                    }
                    let param = {
                        id: this.componentInfo.id,
                        name: this.componentInfo.name,
                        typeName: this.componentInfo.type,
                        fileName: this.componentInfo.path,
                        componentType: this.componentInfo.componentType,
                        attribute: JSON.stringify(attrList)
                    }
                    // if (param) {
                    //     return
                    // }
					console.log('param', attrList)
                    let res = null;
                    if (param.id && this.componentStatus === 'edit') {
                        res = await basicComponent.putComponent(param)
                    } else {
                        res = await basicComponent.addComponent(param)
                    }
                    if (res.status === 1) {
                        this.$message({
                            message: '保存组件成功！',
                            type: 'success'
                        })
                        this.componentInfo = {
                            id: '',
                            componentType: '', // 组件类别
                            name: '',
                            type: '',
                            path: '',
                            attribute: {
                                basicAttr: {},
                                booleanAttr: {},
                                ruleAttr: {},
                                selectAttr: {},
                                requiredAttr: {}
                            }
                        }
                        this.selectAttribute = []
                        this.getComponentList()
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                } else {
                    return false
                }
            })
        }
    }
}
</script>

<style scoped lang="less">
.manage-basic-component {
    height: 100%;
    overflow: hidden hidden;

    .save-btn {
        position: absolute;
        top: 20px;
        right: 15px;
    }

    .label {
        display: inline-block;
        width: 200px;
        text-align: right;
        margin-right: 10px;
        letter-spacing: 2px;
    }

    .change-default {
        width: 350px;
    }
}
</style>
